import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_juwo/common/common_index.dart';
import 'package:flutter_juwo/provider/UserModel.dart';
import 'package:flutter_juwo/ui/controller/MyPageState.dart';
import 'package:flutter_juwo/ui/controller/NetUtils.dart';
import 'package:flutter_juwo/ui/custom/NotLoginPage.dart';
import 'package:flutter_juwo/ui/custom/noData.dart';
import 'package:flutter_juwo/ui/model/message_list_entity.dart';
import 'package:flutter_juwo/ui/res/shared_preferences_keys.dart';
import 'package:flutter_juwo/ui/utils/sp_util.dart';
import 'package:flutter_juwo/ui/utils/toast_utils.dart';

import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_easyrefresh/ball_pulse_header.dart';
import 'package:flutter_easyrefresh/ball_pulse_footer.dart';
import 'package:provider/provider.dart';

import 'model/income_entity.dart';

class MyIncome extends StatefulWidget {
  @override
  _MyIncomeState createState() => _MyIncomeState();
}

class _MyIncomeState extends State<MyIncome>
    with AutomaticKeepAliveClientMixin {
  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;

  IncomeEntity _entity = null;
  MyPageState ps = MyPageState.LOADING;

  EasyRefreshController _easyRefreshController = EasyRefreshController();

  ///当前码
  int _currentPage = 1;

  ///页数默认为1 通过 总数 计算得来
  int _pages = 1;

  ///一页 20 条数据
  int _itemNum = 20;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    this.init();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      appBar: UiUtils.appBar(context, "我的收入"),
      body: Column(
        children: <Widget>[
          UiUtils.divider(),
          getItemTitle(),
          Expanded(
            flex: 1,
            child: getContent(),
          )
        ],
      ),
    );
  }

  getContent() {
    if (ps == MyPageState.LOADING) {
      return LoadingPage();
    }

    if (ps == MyPageState.NOT_DATA) {
      return NoData(this.getData);
    }

    if (ps == MyPageState.HAVE_DATA) {
      if (null == _entity) {
        init();
        return LoadingPage();
      }
      return EasyRefresh.custom(
        controller: _easyRefreshController,

        /// firstRefresh: true,
        enableControlFinishRefresh: true,
        enableControlFinishLoad: true,
        header: BallPulseHeader(),
        footer: BallPulseFooter(),
        onRefresh: () async {
          await Future.delayed(Duration(seconds: 1), () {
            _currentPage = 1;
            this.getData(page: _currentPage);
          });
        },
        onLoad: () async {
          await Future.delayed(Duration(seconds: 1), () {
            if (_currentPage < _pages) {
              _currentPage++;
              this.getData(page: _currentPage);
            } else {
              _easyRefreshController.finishLoad();
              ToastUtil.showShortToast("没有更多了");
            }
          });
        },
        slivers: <Widget>[
          SliverList(
            delegate: SliverChildBuilderDelegate(
              (context, index) {
                return this.getItem(_entity.data.res[index], index);
              },
              childCount: _entity.data.res.length,
            ),
          ),
        ],
      );
    }

    return NoData(this.getData);
  }

  Future getData({int page = 1}) async {
    FormData formData = FormData.from({"page": page, "size": "$_itemNum"});
    DioManager.getInstance().get(Api.USER_INVITEINCOME, formData, (json) {
      IncomeEntity data = IncomeEntity.fromJson(json);
      if (data.code == Api.SUCCESS_CODE) {
        ///1.判断有没有获取到数据
        if (null == data.data.res || data.data.res.length <= 0) {
          this.noData();
          return;
        }

        ///获取页数
        _pages = data.data.total;

        print("页数：$_pages");

        ///2.判断本来有没有数据
        if (null == _entity) {
          _entity = data;
          this.haveData();
          return;
        }

        ///3.下拉刷新数据
        if (page == 1) {
          _currentPage = 1;
          _entity.data.res.clear();
          _entity = data;
          this.haveData();
          _easyRefreshController.finishRefresh(success: true);
          return;
        }

        ///4.上拉加载
        _entity.data.res.addAll(data.data.res);
        this.haveData();
        _easyRefreshController.finishLoad();
        return;
      }

      if (_entity.code == Api.ERROR_CODE_0 || _entity.code == Api.ERROR_CODE) {
        ToastUtil.showShortErrToast(_entity.message);
        return;
      }
    }, (errMsg) {
      ToastUtil.showShortErrToast(errMsg);
    });
  }

  ///没有数据
  void noData() {
    ps = MyPageState.NOT_DATA;
    setState(() {});
  }

  ///有数据
  void haveData() {
    ps = MyPageState.HAVE_DATA;
    setState(() {});
  }

  getItem(IncomeDataRe res, int index) {
    bool isOld = index.isOdd;
    return Container(
      padding: EdgeInsets.only(
          top: ScreenUtil().setWidth(20), bottom: ScreenUtil().setWidth(20)),
      color: isOld ? Colours.white : Colours.c243,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: <Widget>[
          Container(
            child: Text(
              "${res.username}",
              style: TextStyles.custom(
                  28, Colours.appC2, Font.PingFangRegular),
            ),
          ),
          Container(
            child: Text(
              "${res.money}",
              style: TextStyles.custom(
                  28, Colours.appC2, Font.PingFangRegular),
            ),
          ),
          Container(
            child: Text(
              "${res.createTime}",
              style: TextStyles.custom(
                  28, Colours.appC2, Font.PingFangRegular),
            ),
          ),
        ],
      ),
    );
  }

  void init() {
    bool isLogin = NetUtils.isLogin();
    if (isLogin) {
      ///获取数据
      this.getData();
    } else {
      ps = MyPageState.NOT_LOGIN;
    }
  }

  getItemTitle() {
    return Container(
      color: Colors.white,
      padding: EdgeInsets.only(
          top: ScreenUtil().setWidth(20), bottom: ScreenUtil().setWidth(20)),
      child: Row(
        children: <Widget>[
          Expanded(
            flex: 2,
            child: Container(
              child: Text(
                "用户名",
                textAlign: TextAlign.center,
                style: getStyle(),
              ),
            ),
          ),
          Expanded(
            flex: 1,
            child: Container(
              child: Text(
                "入账金额",
                textAlign: TextAlign.center,
                style: getStyle(),
              ),
            ),
          ),
          Expanded(
            flex: 3,
            child: Container(
              child: Text(
                "入账时间",
                textAlign: TextAlign.center,
                style: getStyle(),
              ),
            ),
          ),
        ],
      ),
    );
  }

  getStyle() {
    return TextStyles.custom(30, Colours.appC1, Font.PingFangBlod);
  }
}
